package com.lxl.priv.bak;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.ArrayUtils;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CsvMerger {

    public static void main(String[] args) throws IOException {
        List<String> csvFiles = new ArrayList<>();
        csvFiles.add("D:\\tmp\\1.csv");
        csvFiles.add("D:\\tmp\\2.csv");
        csvFiles.add("D:\\tmp\\3.csv");

        String outputFile = "D:\\tmp\\merged.csv";

        mergeCsvFiles(csvFiles, outputFile);
    }

    public static void mergeCsvFiles(List<String> csvFiles, String outputFile) throws IOException {
        try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(outputFile), CSVFormat.DEFAULT)) {

            for (String csvFile : csvFiles) {
                try (CSVParser csvParser = new CSVParser(new FileReader(csvFile), CSVFormat.DEFAULT)) {
                    List<CSVRecord> records = csvParser.getRecords();
                    for (CSVRecord record : records) {
                        String[] fields = record.values();
                        String newField = "newValue"; // 这里可以设置你想要的值
                        fields = ArrayUtils.add(fields, newField);
                        csvPrinter.printRecord(fields);
                    }
                }
            }
        }
    }
}
